//
//  Login.m
//  Grues
//
//  Created by Miquel Viladomat on 14/12/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "Login.h"
#import "ZonaBlavaAppDelegate.h"

@implementation Login
@synthesize usuari;
@synthesize pass;
@synthesize missatge;

-(IBAction)logejar:(id)sender{
    NSLog(@"va");
    NSString *urlString3 =[NSString stringWithFormat:@"http://www.giroassist.com/picimg/login.php?usuari=%@&password=%@",usuari.text,pass.text];
    NSMutableURLRequest *request3=[[[NSMutableURLRequest alloc] init] autorelease];
    [request3 setURL:[NSURL URLWithString:urlString3]];
    [request3 setHTTPMethod:@"POST"];    
    
    
    conn=[[NSURLConnection alloc]initWithRequest:request3 delegate:self];
    if (conn) {
        webData = [[NSMutableData data] retain];
    }    
}
-(IBAction)dismiss{
    [self resignFirstResponder];
}

-(void) connection:(NSURLConnection *) connection 
didReceiveResponse:(NSURLResponse *) response {
    NSLog(@"va");
    [webData setLength: 0];
}
-(void) connection:(NSURLConnection *) connection 
    didReceiveData:(NSData *) data {
    NSLog(@"niva");
    [webData appendData:data];
}
-(void) connection:(NSURLConnection *) connection 
  didFailWithError:(NSError *) error {
    NSLog(error.localizedDescription);
    [webData release];
    [connection release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
    NSLog(@"DONE. Received Bytes: %d", [webData length]);
    NSString *theXML = [[NSString alloc] 
                        initWithBytes: [webData mutableBytes] 
                        length:[webData length] 
                        encoding:NSUTF8StringEncoding];
    //---shows the XML---
    NSLog(@"text:%@",theXML);
    
    if (xmlParser)
    {
        [xmlParser release];
    }    
    xmlParser = [[NSXMLParser alloc] initWithData: webData];
    [xmlParser setDelegate: self];
    [xmlParser setShouldResolveExternalEntities:YES];
    [xmlParser parse];
    
    [theXML release];     
    
    [connection release];
    [webData release];
}
-(void) parser:(NSXMLParser *) parser 
didStartElement:(NSString *) elementName 
  namespaceURI:(NSString *) namespaceURI 
 qualifiedName:(NSString *) qName
    attributes:(NSDictionary *) attributeDict {
    
    if( [elementName isEqualToString:@"Validacio"])
    {
        if (!soapResults)
        {
            soapResults = [[NSMutableString alloc] init];
        }
        elementFound = YES;
    }
}
-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string
{
    if (elementFound)
    {
        [soapResults appendString: string];
    }
}
-(void)parser:(NSXMLParser *)parser 
didEndElement:(NSString *)elementName 
 namespaceURI:(NSString *)namespaceURI 
qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@"Validacio"])
    {
        if ([soapResults isEqualToString:@"error"])
        {
            [missatge setText:@"Indentificació incorrecte"];
        }  
        else{
            ZonaBlavaAppDelegate *dataCenter=(ZonaBlavaAppDelegate *)[[UIApplication sharedApplication] delegate];
            dataCenter.codiagentv=soapResults;
            dataCenter.estat=@"entrant";
            
            //NSTimeInterval seconds; // assume this exists
            NSDate* ts_utc = [NSDate date];
            NSDateFormatter* df_local = [[[NSDateFormatter alloc] init] autorelease];
            [df_local setTimeZone:[NSTimeZone timeZoneWithName:@"GMT+1"]];
            [df_local setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
            NSString* strDate = [df_local stringFromDate:ts_utc];
            //NSDate *now = [NSDate date];
            NSArray *arr = [strDate componentsSeparatedByString:@" "];
            NSString *str;
            str = [arr objectAtIndex:0];
            
            NSArray *arr_my = [str componentsSeparatedByString:@"-"];
            
            dataCenter.datav=[NSString stringWithFormat:@"%@/%@/%@",[arr_my objectAtIndex:2],[arr_my objectAtIndex:1],[arr_my objectAtIndex:0]];
            str = [arr objectAtIndex:1];
            NSArray *arr_my2 = [str componentsSeparatedByString:@":"];
            dataCenter.horav=[NSString stringWithFormat:@"%@:%@",[arr_my2 objectAtIndex:0],[arr_my2 objectAtIndex:1]];
            [self.parentViewController dismissModalViewControllerAnimated:true];
        } 
    }
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
